package com.hejl.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * @author Hejl
 * @version 1.0
 * @description
 * @className AudioModelController
 * @date 2025/6/11 3:05
 */
@RestController
public class AudioModelController {
    private static final String TEXT = "床前明月光， 疑是地上霜。 举头望明月， 低头思故乡。";
    private static final String FILE_PATH = "file/tts";
    @Autowired
    private DashScopeSpeechSynthesisModel speechModel;

    /**
     * 语音合成
     */
    @GetMapping("/audio")
    public void audio() throws IOException {
        DashScopeSpeechSynthesisOptions options = DashScopeSpeechSynthesisOptions.builder()
                .withSpeed(1.0)//语速
                .withPitch(1.0)//音调
                .withVolume(30)//音量
                .build();
        SpeechSynthesisResponse response = speechModel.call(new SpeechSynthesisPrompt(TEXT, options));
        File directory = new File(FILE_PATH);
        if (!directory.exists()) {
            directory.mkdirs(); // 自动创建所有必要的父目录
        }
        File file = new File(FILE_PATH + "/output.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
        } catch (IOException e) {
            throw new IOException("写入音频失败："+e.getMessage(),e);
        }

    }
}